<template>
	<div class="sys-job-container">
		<el-card shadow="hover" :body-style="{ padding: '5px 5px 0 5px', display: 'flex', width: '100%', height: '100%', alignItems: 'start' }">
			<el-form :model="state.queryParams" ref="queryForm" :show-message="false" :inlineMessage="true" label-width="auto" style="flex: 1 1 0%">
				<el-row :gutter="10">
					<el-col class="mb5" :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
						<el-form-item label="作业编号" prop="jobId">
							<el-input v-model="state.queryParams.jobId" placeholder="作业编号" clearable @keyup.enter.native="handleQuery(true)" />
						</el-form-item>
					</el-col>
					<el-col class="mb5" :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
						<el-form-item label="描述信息" prop="description">
							<el-input v-model="state.queryParams.description" placeholder="描述信息" clearable @keyup.enter.native="handleQuery(true)" />
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<el-divider style="height: calc(100% - 5px); margin: 0 10px" direction="vertical" />
			<el-row>
				<el-col>
					<el-button-group>
						<el-button type="primary" icon="ele-Search" @click="handleQuery(true)" v-auth="'sysJob/pageJobDetail'" :loading="options.loading"> 查询 </el-button>
						<el-button icon="ele-Refresh" @click="resetQuery" :loading="options.loading"> 重置 </el-button>
					</el-button-group>
				</el-col>
			</el-row>
		</el-card>

		<el-card class="full-table" shadow="hover" style="margin-top: 5px">
			<vxe-grid ref="xGrid" class="xGrid-style" v-bind="options" @sort-change="sortChange">
				<template #toolbar_buttons>
					<el-button-group>
						<el-tooltip content="增加作业">
							<el-button icon="ele-CirclePlus" @click="handleAdd" v-auth="'sysJob/addJobDetail'"> </el-button>
						</el-tooltip>
						<el-tooltip content="启动所有作业">
							<el-button icon="ele-VideoPlay" @click="startAllJob" />
						</el-tooltip>
						<el-tooltip content="暂停所有作业">
							<el-button icon="ele-VideoPause" @click="pauseAllJob" />
						</el-tooltip>
					</el-button-group>
					<el-button-group style="margin: 0 12px">
						<el-tooltip content="强制唤醒作业调度器">
							<el-button icon="ele-AlarmClock" @click="cancelSleep" />
						</el-tooltip>
						<el-tooltip content="强制触发所有作业持久化">
							<el-button icon="ele-Connection" @click="persistAll" />
						</el-tooltip>
					</el-button-group>
					<el-button icon="ele-Coin" @click="openJobCluster" plain> 集群控制 </el-button>
					<el-button icon="ele-Grid" @click="openJobDashboard" plain> 任务看板 </el-button>
					<el-button-group style="padding-left: 12px">
						<el-button type="primary" icon="ele-Expand" @click="handleExpand"> 全部展开 </el-button>
						<el-button type="primary" icon="ele-Fold" @click="handleFold"> 全部折叠 </el-button>
					</el-button-group>
				</template>
				<template #toolbar_tools> </template>
				<template #empty>
					<el-empty :image-size="200" />
				</template>
				<template #row_content="scope">
					<vxe-table style="margin: 5px" align="center" :data="(scope.row as JobDetailOutput).jobTriggers">
						<!-- <vxe-column type="checkbox" width="40" fixed="left"></vxe-column>  -->
						<vxe-column type="seq" width="40" fixed="left"></vxe-column>
						<vxe-column field="triggerId" title="触发器编号" :minWidth="180" showOverflow="tooltip"></vxe-column>
						<vxe-column field="triggerType" title="类型" :minWidth="120" showOverflow="tooltip"></vxe-column>
						<!-- <vxe-column field="assemblyName" title="程序集" :minWidth="120" showOverflow="tooltip"></vxe-column> -->
						<vxe-column field="args" title="参数" :minWidth="120" showOverflow="tooltip"></vxe-column>
						<vxe-column field="description" title="描述" :minWidth="120" showOverflow="tooltip"></vxe-column>
						<vxe-column field="status" title="状态" :minWidth="120" showOverflow="tooltip">
							<template #default="{ row }">
								<el-tag type="warning" effect="plain" v-if="(row as SysJobTrigger).status == 0"> 积压 </el-tag>
								<el-tag type="info" effect="plain" v-if="(row as SysJobTrigger).status == 1"> 就绪 </el-tag>
								<el-tag type="success" effect="plain" v-if="(row as SysJobTrigger).status == 2"> 正在运行 </el-tag>
								<el-tag type="danger" effect="plain" v-if="(row as SysJobTrigger).status == 3"> 暂停 </el-tag>
								<el-tag type="danger" effect="plain" v-if="(row as SysJobTrigger).status == 4"> 阻塞 </el-tag>
								<el-tag type="info" effect="plain" v-if="(row as SysJobTrigger).status == 5"> 由失败进入就绪 </el-tag>
								<el-tag type="danger" effect="plain" v-if="(row as SysJobTrigger).status == 6"> 归档 </el-tag>
								<el-tag type="danger" effect="plain" v-if="(row as SysJobTrigger).status == 7"> 崩溃 </el-tag>
								<el-tag type="danger" effect="plain" v-if="(row as SysJobTrigger).status == 8"> 超限 </el-tag>
								<el-tag type="danger" effect="plain" v-if="(row as SysJobTrigger).status == 9"> 无触发时间 </el-tag>
								<el-tag type="danger" effect="plain" v-if="(row as SysJobTrigger).status == 10"> 未启动 </el-tag>
								<el-tag type="danger" effect="plain" v-if="(row as SysJobTrigger).status == 11"> 未知作业触发器 </el-tag>
								<el-tag type="danger" effect="plain" v-if="(row as SysJobTrigger).status == 12"> 未知作业处理程序 </el-tag>
							</template>
						</vxe-column>
						<vxe-column field="startTime" title="起始时间" :minWidth="100" showOverflow="tooltip"></vxe-column>
						<vxe-column field="endTime" title="结束时间" :minWidth="100" showOverflow="tooltip"></vxe-column>
						<vxe-column field="lastRunTime" title="最近运行时间" :minWidth="130" showOverflow="tooltip"></vxe-column>
						<vxe-column field="nextRunTime" title="下一次运行时间" :minWidth="130" showOverflow="tooltip"></vxe-column>
						<vxe-column field="numberOfRuns" title="触发次数" :minWidth="70" showOverflow="tooltip"></vxe-column>
						<vxe-column field="maxNumberOfRuns" title="最大触发次数" :minWidth="90" showOverflow="tooltip"></vxe-column>
						<vxe-column field="numberOfErrors" title="出错次数" :minWidth="70" showOverflow="tooltip"></vxe-column>
						<vxe-column field="maxNumberOfErrors" title="最大出错次数" :minWidth="90" showOverflow="tooltip"></vxe-column>
						<vxe-column field="numRetries" title="重试次数" :minWidth="70" showOverflow="tooltip"></vxe-column>
						<vxe-column field="retryTimeout" title="重试间隔ms" :minWidth="80" showOverflow="tooltip"></vxe-column>
						<vxe-column field="startNow" title="是否立即启动" :minWidth="90" showOverflow="tooltip">
							<template #default="scope">
								<el-tag v-if="(scope.row as SysJobTrigger).startNow == true"> 是 </el-tag>
								<el-tag type="info" v-else> 否 </el-tag>
							</template>
						</vxe-column>
						<vxe-column field="runOnStart" title="是否启动时执行一次" :minWidth="120" showOverflow="tooltip">
							<template #default="scope">
								<el-tag v-if="(scope.row as SysJobTrigger).runOnStart == true"> 是 </el-tag>
								<el-tag type="info" v-else> 否 </el-tag>
							</template>
						</vxe-column>
						<vxe-column field="resetOnlyOnce" title="是否重置触发次数" :minWidth="110" showOverflow="tooltip">
							<template #default="scope">
								<el-tag v-if="(scope.row as SysJobTrigger).resetOnlyOnce == true"> 是 </el-tag>
								<el-tag type="info" v-else> 否 </el-tag>
							</template>
						</vxe-column>
						<vxe-column title="操作" :minWidth="130" fixed="right">
							<template #default="scope">
								<el-tooltip content="启动触发器">
									<el-button size="small" type="primary" icon="ele-VideoPlay" text @click="startTrigger(scope.row)" />
								</el-tooltip>
								<el-tooltip content="暂停触发器">
									<el-button size="small" type="primary" icon="ele-VideoPause" text @click="pauseTrigger(scope.row)" />
								</el-tooltip>
								<el-tooltip content="编辑触发器">
									<el-button size="small" type="primary" icon="ele-Edit" text @click="openEditJobTrigger(scope.row)"> </el-button>
								</el-tooltip>
								<el-tooltip content="删除触发器">
									<el-button size="small" type="danger" icon="ele-Delete" text @click="delJobTrigger(scope.row)"> </el-button>
								</el-tooltip>
							</template>
						</vxe-column>
					</vxe-table>
				</template>
				<template #row_jobId="{ row }">
					<div style="display: flex; align-items: center">
						<el-icon><timer /></el-icon>
						<span style="margin-left: 5px">{{ (row as JobDetailOutput).jobDetail?.jobId }}</span>
					</div>
				</template>
				<template #row_concurrent="{ row }">
					<el-tag type="success" v-if="(row as JobDetailOutput).jobDetail?.concurrent == true"> 并行 </el-tag>
					<el-tag type="warning" v-else> 串行 </el-tag>
				</template>
				<template #row_createType="{ row }">
					<el-tag type="info" v-if="(row as JobDetailOutput).jobDetail?.createType == JobCreateTypeEnum.NUMBER_0"> 内置 </el-tag>
					<el-tag type="warning" v-if="(row as JobDetailOutput).jobDetail?.createType == JobCreateTypeEnum.NUMBER_1"> 脚本 </el-tag>
					<el-tag type="success" v-if="(row as JobDetailOutput).jobDetail?.createType == JobCreateTypeEnum.NUMBER_2"> HTTP请求 </el-tag>
				</template>
				<template #row_includeAnnotations="{ row }">
					<el-tag v-if="(row as JobDetailOutput).jobDetail?.includeAnnotations == true"> 是 </el-tag>
					<el-tag v-else> 否 </el-tag>
				</template>
				<template #row_properties="{ row }">
					<span v-if="(row as JobDetailOutput).jobDetail?.createType != JobCreateTypeEnum.NUMBER_2"> {{ (row as JobDetailOutput).jobDetail?.properties }} </span>
					<div v-else style="text-align: center">
						<el-popover placement="left" :width="400" trigger="hover">
							<template #reference>
								<el-tag effect="plain" type="info"> 请求参数 </el-tag>
							</template>
							<el-descriptions title="Http 请求参数" :column="1" size="small" :border="true">
								<el-descriptions-item label="请求地址" label-align="right" label-class-name="job-index-descriptions-label-style">
									{{ getHttpJobMessage((row as JobDetailOutput).jobDetail?.properties).requestUri }}
								</el-descriptions-item>
								<el-descriptions-item label="请求方法" label-align="right" label-class-name="job-index-descriptions-label-style">
									{{ getHttpMethodDesc(getHttpJobMessage((row as JobDetailOutput).jobDetail?.properties).httpMethod) }}
								</el-descriptions-item>
								<el-descriptions-item label="请求报文体" label-align="right" label-class-name="job-index-descriptions-label-style">
									{{ getHttpJobMessage((row as JobDetailOutput).jobDetail?.properties).body }}
								</el-descriptions-item>
							</el-descriptions>
						</el-popover>
					</div>
				</template>
				<template #row_buttons="{ row }">
					<el-tooltip content="执行记录">
						<el-button size="small" type="primary" icon="ele-Timer" text @click="openJobTriggerRecord(row)"> </el-button>
					</el-tooltip>
					<el-tooltip content="增加触发器">
						<el-button size="small" type="primary" icon="ele-CirclePlus" text @click="openAddJobTrigger(row)"> </el-button>
					</el-tooltip>
					<el-tooltip content="执行作业">
						<el-button size="small" type="primary" icon="ele-CircleCheck" text @click="runJob(row)" />
					</el-tooltip>
					<el-tooltip content="启动作业">
						<el-button size="small" type="primary" icon="ele-VideoPlay" text @click="startJob(row)" />
					</el-tooltip>
					<el-tooltip content="暂停作业">
						<el-button size="small" type="primary" icon="ele-VideoPause" text @click="pauseJob(row)" />
					</el-tooltip>
					<el-tooltip content="取消作业">
						<el-button size="small" type="primary" icon="ele-CircleClose" text @click="cancelJob(row)" />
					</el-tooltip>
					<el-tooltip content="编辑作业">
						<el-button size="small" type="primary" icon="ele-Edit" text @click="handleEdit(row)" v-auth="'sysJob/updateJobDetail'"> </el-button>
					</el-tooltip>
					<el-tooltip content="删除作业">
						<el-button size="small" type="danger" icon="ele-Delete" text @click="handleDelete(row)" v-auth="'sysJob/deleteJobDetail'"> </el-button>
					</el-tooltip>
				</template>
				<template #pager>
					<vxe-pager
						:loading="options.loading"
						v-model:current-page="state.tableParams.page"
						v-model:page-size="state.tableParams.pageSize"
						:total="state.tableParams.total"
						@page-change="pageChange"
					/>
				</template>
			</vxe-grid>
		</el-card>

		<el-drawer v-model="state.isVisibleDrawer" size="60%">
			<template #header>
				<div style="color: #fff">
					<el-icon size="16" style="margin-right: 3px; display: inline; vertical-align: middle"> <ele-Clock /> </el-icon>
					<span> 作业触发器运行记录</span>
				</div>
			</template>
			<el-card class="full-table" shadow="hover">
				<vxe-grid ref="xRecordGrid" class="xGrid-style" v-bind="recordOptions" @sort-change="recordSortChange">
					<template #toolbar_buttons></template>
					<template #toolbar_tools> </template>
					<template #empty>
						<el-empty :image-size="200" />
					</template>
					<template #row_status="{ row }">
						<el-tag type="warning" effect="plain" v-if="(row as SysJobTrigger).status == 0"> 积压 </el-tag>
						<el-tag type="info" effect="plain" v-if="(row as SysJobTrigger).status == 1"> 就绪 </el-tag>
						<el-tag type="success" effect="plain" v-if="(row as SysJobTrigger).status == 2"> 正在运行 </el-tag>
						<el-tag type="danger" effect="plain" v-if="(row as SysJobTrigger).status == 3"> 暂停 </el-tag>
						<el-tag type="danger" effect="plain" v-if="(row as SysJobTrigger).status == 4"> 阻塞 </el-tag>
						<el-tag type="info" effect="plain" v-if="(row as SysJobTrigger).status == 5"> 由失败进入就绪 </el-tag>
						<el-tag type="danger" effect="plain" v-if="(row as SysJobTrigger).status == 6"> 归档 </el-tag>
						<el-tag type="danger" effect="plain" v-if="(row as SysJobTrigger).status == 7"> 崩溃 </el-tag>
						<el-tag type="danger" effect="plain" v-if="(row as SysJobTrigger).status == 8"> 超限 </el-tag>
						<el-tag type="danger" effect="plain" v-if="(row as SysJobTrigger).status == 9"> 无触发时间 </el-tag>
						<el-tag type="danger" effect="plain" v-if="(row as SysJobTrigger).status == 10"> 未启动 </el-tag>
						<el-tag type="danger" effect="plain" v-if="(row as SysJobTrigger).status == 11"> 未知作业触发器 </el-tag>
						<el-tag type="danger" effect="plain" v-if="(row as SysJobTrigger).status == 12"> 未知作业处理程序 </el-tag>
					</template>
					<template #pager>
						<vxe-pager
							:loading="recordOptions.loading"
							v-model:current-page="state.recordTableParams.page"
							v-model:page-size="state.recordTableParams.pageSize"
							:total="state.recordTableParams.total"
							@page-change="recordPageChange"
						/>
					</template>
				</vxe-grid>
			</el-card>
		</el-drawer>

		<EditJobDetail ref="editJobDetailRef" :title="state.editJobDetailTitle" @handleQuery="handleQuery" />
		<EditJobTrigger ref="editJobTriggerRef" :title="state.editJobTriggerTitle" @handleQuery="handleQuery" />
		<JobCluster ref="editJobClusterRef" />
	</div>
</template>

<script lang="ts" setup name="sysJob">
import { onMounted, reactive, ref } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import { auth } from '/@/utils/authFunction';
import { VxeGridInstance, VxePagerEvents, VxePagerDefines } from 'vxe-table';
import { useVxeTable } from '/@/hooks/vxeTableOptionsHook';
import { useRouter } from 'vue-router';
import { Timer } from '@element-plus/icons-vue';

import EditJobDetail from '/@/views/system/job/component/editJobDetail.vue';
import EditJobTrigger from '/@/views/system/job/component/editJobTrigger.vue';
import JobCluster from '/@/views/system/job/component/jobCluster.vue';

import { getAPI } from '/@/utils/axios-utils';
import { SysJobApi } from '/@/api-services/api';
import { JobCreateTypeEnum, JobDetailOutput, SysJobTrigger, SysJobTriggerRecord } from '/@/api-services/models';

const xGrid = ref<VxeGridInstance>();
const xRecordGrid = ref<VxeGridInstance>();
const router = useRouter();
const editJobDetailRef = ref<InstanceType<typeof EditJobDetail>>();
const editJobTriggerRef = ref<InstanceType<typeof EditJobTrigger>>();
const editJobClusterRef = ref<InstanceType<typeof JobCluster>>();
const state = reactive({
	queryParams: {
		jobId: undefined,
		description: undefined,
	},
	tableParams: {
		page: 1,
		pageSize: 50,
		field: 'id', // 默认的排序字段
		order: 'aes', // 排序方向
		descStr: 'desc', // 降序排序的关键字符
		total: 0 as any,
	},
	recordTableParams: {
		page: 1,
		pageSize: 50,
		field: 'id', // 默认的排序字段
		order: 'desc', // 排序方向
		descStr: 'desc', // 降序排序的关键字符
		total: 0 as any,
	},
	editJobDetailTitle: '',
	editJobTriggerTitle: '',
	loading2: false,
	isVisibleDrawer: false,
	triggerRecordData: [] as any,
	currentJob: {} as any,
	visible: false,
	title: '',
});

// 表格参数配置
const options = useVxeTable<JobDetailOutput>({
	id: 'sysJob',
	name: '作业信息',
	columns: [
		// { type: 'checkbox', width: 40 },
		{ type: 'seq', title: '序号', width: 50, fixed: 'left' },
		{ type: 'expand', width: 40, slots: { content: 'row_content' } },
		{ field: 'jobDetail.jobId', title: '作业编号', minWidth: 180, showOverflow: 'tooltip', slots: { default: 'row_jobId' } },
		{ field: 'jobDetail.groupName', title: '组名称', minWidth: 80, showOverflow: 'tooltip' },
		{ field: 'jobDetail.jobType', title: '类型', minWidth: 180, showOverflow: 'tooltip' },
		// { field: 'jobDetail.assemblyName', title: '程序集', minWidth: 100, showOverflow: 'tooltip', sortable: true },
		{ field: 'jobDetail.description', title: '描述', minWidth: 150, showOverflow: 'tooltip' },
		{ field: 'jobDetail.concurrent', title: '执行方式', minWidth: 80, showOverflow: 'tooltip', slots: { default: 'row_concurrent' } },
		{ field: 'jobDetail.createType', title: '作业创建类型', minWidth: 100, showOverflow: 'tooltip', slots: { default: 'row_createType' } },
		{ field: 'jobDetail.includeAnnotations', title: '扫描特性触发器', minWidth: 120, showOverflow: 'tooltip', slots: { default: 'row_includeAnnotations' } },
		{ field: 'jobDetail.updatedTime', title: '更新时间', minWidth: 130, showOverflow: 'tooltip' },
		{ field: 'jobDetail.properties', title: '额外数据', minWidth: 140, showOverflow: 'tooltip', slots: { default: 'row_properties' } },
		{ title: '操作', minWidth: 200, showOverflow: true, slots: { default: 'row_buttons' } },
	],
	enableExport: auth('sysJob:export'),
	searchCallback: () => handleQuery(),
	queryAllCallback: () => fetchData({ pageSize: 99999 }),
});

// 页面初始化
onMounted(async () => {
	await handleQuery();
});

// 查询操作
const handleQuery = async (reset = false) => {
	options.loading = true;
	if (reset) state.tableParams.page = 1;
	var res = await fetchData(null);
	await xGrid.value?.loadData(res.data.result?.items ?? []);
	state.tableParams.total = res.data.result?.total;
	options.loading = false;
};

// 获取数据
const fetchData = async (tableParams: any) => {
	let params = Object.assign(state.queryParams, state.tableParams, tableParams);
	return getAPI(SysJobApi).apiSysJobPageJobDetailPost(params);
};

// 重置操作
const resetQuery = async () => {
	state.queryParams.jobId = undefined;
	state.queryParams.description = undefined;
	await handleQuery(true);
};

// 改变页码序号或页面容量
const pageChange: VxePagerEvents.PageChange = async ({ currentPage, pageSize }: VxePagerDefines.PageChangeEventParams) => {
	state.tableParams.page = currentPage;
	state.tableParams.pageSize = pageSize;
	await handleQuery();
};

// 列排序
const sortChange = async (options: any) => {
	state.tableParams.field = options.field;
	state.tableParams.order = options.order;
	await handleQuery();
};

// 打开新增作业页面
const handleAdd = () => {
	state.editJobDetailTitle = '添加作业';
	editJobDetailRef.value?.openDialog({ concurrent: true, includeAnnotations: true, groupName: 'default', createType: JobCreateTypeEnum.NUMBER_2 });
};

// 打开编辑作业页面
const handleEdit = (row: JobDetailOutput) => {
	state.editJobDetailTitle = '编辑作业';
	editJobDetailRef.value?.openDialog(row.jobDetail);
};

// 删除作业
const handleDelete = (row: JobDetailOutput) => {
	ElMessageBox.confirm(`确定删除作业：【${row.jobDetail?.jobId}】?`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(async () => {
			await getAPI(SysJobApi).apiSysJobDeleteJobDetailPost({ jobId: row.jobDetail?.jobId });
			handleQuery();
			ElMessage.success('删除成功');
		})
		.catch(() => {});
};

// 打开新增触发器页面
const openAddJobTrigger = (row: JobDetailOutput) => {
	state.editJobTriggerTitle = '添加触发器';
	editJobTriggerRef.value?.openDialog({
		jobId: row.jobDetail?.jobId,
		retryTimeout: 1000,
		startNow: true,
		runOnStart: true,
		resetOnlyOnce: true,
		triggerType: 'Furion.Schedule.PeriodTrigger',
	});
};

// 打开编辑触发器页面
const openEditJobTrigger = (row: SysJobTrigger) => {
	state.editJobTriggerTitle = '编辑触发器';
	editJobTriggerRef.value?.openDialog(row);
};

// 删除触发器
const delJobTrigger = (row: SysJobTrigger) => {
	ElMessageBox.confirm(`确定删除触发器：【${row.triggerId}】?`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(async () => {
			await getAPI(SysJobApi).apiSysJobDeleteJobTriggerPost({ jobId: row.jobId, triggerId: row.triggerId });
			handleQuery();
			ElMessage.success('删除成功');
		})
		.catch(() => {});
};

// 启动所有作业
const startAllJob = async () => {
	await getAPI(SysJobApi).apiSysJobStartAllJobPost();
	ElMessage.success('启动所有作业');
};

// 暂停所有作业
const pauseAllJob = async () => {
	await getAPI(SysJobApi).apiSysJobPauseAllJobPost();
	ElMessage.success('暂停所有作业');
};

// 执行某个作业
const runJob = async (row: JobDetailOutput) => {
	await getAPI(SysJobApi).apiSysJobRunJobPost({ jobId: row.jobDetail?.jobId });
	ElMessage.success('执行作业');
};

// 启动某个作业
const startJob = async (row: JobDetailOutput) => {
	await getAPI(SysJobApi).apiSysJobStartJobPost({ jobId: row.jobDetail?.jobId });
	ElMessage.success('启动作业');
};

// 暂停某个作业
const pauseJob = async (row: JobDetailOutput) => {
	await getAPI(SysJobApi).apiSysJobPauseJobPost({ jobId: row.jobDetail?.jobId });
	ElMessage.success('暂停作业');
};

// 取消某个作业
const cancelJob = async (row: JobDetailOutput) => {
	await getAPI(SysJobApi).apiSysJobCancelJobPost({ jobId: row.jobDetail?.jobId });
	ElMessage.success('取消作业');
};

// 启动触发器
const startTrigger = async (row: SysJobTrigger) => {
	await getAPI(SysJobApi).apiSysJobStartTriggerPost({ jobId: row.jobId, triggerId: row.triggerId });
	ElMessage.success('启动触发器');
};

// 暂停触发器
const pauseTrigger = async (row: SysJobTrigger) => {
	await getAPI(SysJobApi).apiSysJobPauseTriggerPost({ jobId: row.jobId, triggerId: row.triggerId });
	ElMessage.success('暂停触发器');
};

// 强制唤醒作业调度器
const cancelSleep = async () => {
	await getAPI(SysJobApi).apiSysJobCancelSleepPost();
	ElMessage.success('强制唤醒作业调度器');
};

// 强制触发所有作业持久化
const persistAll = async () => {
	await getAPI(SysJobApi).apiSysJobPersistAllPost();
	ElMessage.success('强制触发所有作业持久化');
};

// 打开集群控制页面
const openJobCluster = () => {
	editJobClusterRef.value?.openDrawer();
};

// 打开任务看板
const openJobDashboard = () => {
	router.push({
		path: '/platform/job/dashboard',
	});
};

// 根据任务属性获取 HttpJobMessage
const getHttpJobMessage = (properties: string | undefined | null): HttpJobMessage => {
	if (properties === undefined || properties === null || properties === '') return {};
	const propData = JSON.parse(properties);
	const httpJobMessageNet = JSON.parse(propData['HttpJob']); // 后端大写开头的 HttpJobMessage
	return {
		requestUri: httpJobMessageNet.RequestUri,
		httpMethod: JSON.stringify(httpJobMessageNet.HttpMethod),
		body: httpJobMessageNet.Body,
	};
};

// 获取请求方法的对应描述
const getHttpMethodDesc = (httpMethodStr: string | undefined | null): string => {
	if (httpMethodStr === undefined || httpMethodStr === null || httpMethodStr === '') return '';
	for (const key in editJobDetailRef.value?.httpMethodDef) {
		if (editJobDetailRef.value?.httpMethodDef[key] === httpMethodStr) return key;
	}
	return '';
};

//全部展开
const handleExpand = () => {
	xGrid.value?.setAllRowExpand(true);
};

//全部折叠
const handleFold = () => {
	xGrid.value?.clearRowExpand();
};

// 打开作业触发器运行记录
const openJobTriggerRecord = async (row: any) => {
	state.currentJob = row;
	state.isVisibleDrawer = true;
	await handleQueryRecord();
};

// 表格参数配置-触发器
const recordOptions = useVxeTable<SysJobTriggerRecord>({
	id: 'sysJobRecord',
	name: '执行记录',
	columns: [
		// { type: 'checkbox', width: 40, fixed: 'left' },
		{ type: 'seq', title: '序号', width: 50, fixed: 'left' },
		{ field: 'jobId', title: '作业编号', minWidth: 200, showOverflow: 'tooltip' },
		{ field: 'triggerId', title: '触发器编号', minWidth: 200, showOverflow: 'tooltip' },
		{ field: 'numberOfRuns', title: '当前运行次数', minWidth: 100, showOverflow: 'tooltip' },
		{ field: 'lastRunTime', title: '最近运行时间', minWidth: 130, showOverflow: 'tooltip' },
		{ field: 'nextRunTime', title: '下一次运行时间', minWidth: 130, showOverflow: 'tooltip' },
		{ field: 'status', title: '触发器状态', minWidth: 110, showOverflow: 'tooltip', slots: { default: 'row_status' } },
		{ field: 'result', title: '执行结果', minWidth: 200, showOverflow: 'title' },
		{ field: 'elapsedTime', title: '耗时(ms)', minWidth: 80, showOverflow: 'tooltip' },
		{ field: 'createdTime', title: '创建时间', minWidth: 130, showOverflow: 'tooltip' },
	],
	searchCallback: () => handleQueryRecord(),
	queryAllCallback: () => fetchRecordData({ pageSize: 99999 }),
});

// 查询操作
const handleQueryRecord = async (reset = false) => {
	recordOptions.loading = true;
	if (reset) state.recordTableParams.page = 1;
	var res = await fetchRecordData(null);
	await xRecordGrid.value?.loadData(res.data.result?.items ?? []);
	state.recordTableParams.total = res.data.result?.total;
	recordOptions.loading = false;
};

// 获取数据
const fetchRecordData = async (tableParams: any) => {
	let params = Object.assign({ jobId: state.currentJob.jobDetail.jobId }, state.recordTableParams, tableParams);
	return getAPI(SysJobApi).apiSysJobPageJobTriggerRecordPost(params);
};

// 改变页码序号或页面容量
const recordPageChange: VxePagerEvents.PageChange = async ({ currentPage, pageSize }: VxePagerDefines.PageChangeEventParams) => {
	state.recordTableParams.page = currentPage;
	state.recordTableParams.pageSize = pageSize;
	await handleQueryRecord();
};

// 列排序
const recordSortChange = async (options: any) => {
	state.recordTableParams.field = options.field;
	state.recordTableParams.order = options.order;
	await handleQueryRecord();
};
</script>

<style>
/* 此样式不能为 scoped */
.job-index-descriptions-label-style {
	width: 80px;
}
</style>

<style lang="scss" scoped>
:deep(.el-drawer__body) {
	padding: 5px;
	display: flex;
	flex-direction: column;
	height: 100%;
}
.full-table {
	flex: 1;

	:deep(.el-card__body) {
		height: 100%;
		display: flex;
		flex-direction: column;
	}
}
</style>
